## perfect.asm
## 
## Program to calculate a perfect number
##
## Register Use:
##  $v0    Holds number to be tested
##  $t0    Holds the sums of all the factors
##  $t1    Loop counter
##  $t2    Temporaty holds factos
##  $t3    holds remainders
##  $t4    Half the size of the number
##  $t5    
##  $t6    

        .text
        .globl  main

main:   
        li    $t0,1              # Sets factor sum to 1
        li    $t1,0              # init loop counter                  
        li    $t2,0              # clears temporary factors
        li    $t3,0              # zero the remainder
        li    $v0,4              # syscall for Print String
        la    $a0, prompt1       # load address of prompt into $a0
        nop
        nop
        syscall                  # print the prompt
        li    $v0,5              # Reads user number
        nop
        nop
        syscall
        blt   $v0,$0,flaw        # Negative number automaticly gets flawed
        nop
        subu  $t0,$t0,$v0        # converts number to negative
        div   $t4,$v0,2          # Sets the loop to half the number
for:            
        beq   $t1,$t4,endfor     # for ( i=0; i < $v1 ;i++ )
        addu  $t1,$t1,1          # increment counter
        remu  $t3,$v0,$t1        # Determines if number($v1) is a factorable with respect to counter($t1)
        bne   $0,$t3,for         # if the number is a factor, continue, else restart loop
        nop         
        div   $t2,$v0,$t1        # Determines a factor of the number
        addu  $t0,$t0,$t2        # Adds the factor to $t0
        b     for                # Goes to the beggining of the loop
endfor:
        bne     $v0,$t0,flaw     # If the entered number does not equals it's sum of the factors, go to flaw
        nop
        li      $v0,4            # code 4 == print string             
        la      $a0,perfect      # $a0 ==  of the string
        nop
        nop
        syscall                  # Invoke the exception handler.
        j       endof            # end of program
        nop
flaw:
        beq     $v1,$t0,endof
        nop
        li      $v0,4            # code 4 == print string
        la      $a0,flawed       # $a0 == address of the string
        nop
        nop
        syscall                  # Invoke the exception handler.
endof:        
        li      $v0,10           # code 10 == exit
        nop
        nop
        syscall                  # Halt the program.
        nop
        nop
        nop

         .data
prompt1: .asciiz "Input any number, and I will tell you if it is perfect!"
perfect: .asciiz "This is as perfect as a number can get!!!"
flawed:  .asciiz "This number is flawed, GET A NEW ONE!!!"